using AutoMapper;
using MediatR;
using ProduceBasicData.Api.Application.Command.WarehouseManage;
using ProduceBasicData.Domain.WarehouseManage;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.WarehouseManage
{
    /// <summary>
    /// 更新出库单处理器
    /// </summary>
    public class UpdateStockOutOrderHandler : IRequestHandler<UpdateStockOutOrderCommand, ApiResult<int>>
    {
        private readonly IBaseRespository<StockOutOrder> _stockOutOrderRepository;
        private readonly IMapper _mapper;

        public UpdateStockOutOrderHandler(IBaseRespository<StockOutOrder> stockOutOrderRepository, IMapper mapper)
        {
            _stockOutOrderRepository = stockOutOrderRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 处理更新出库单请求
        /// </summary>
        /// <param name="request">更新出库单命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult<int>> Handle(UpdateStockOutOrderCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 获取出库单信息
                var stockOutOrder = await _stockOutOrderRepository.GetModelAsync(request.Id);
                if (stockOutOrder == null||stockOutOrder.Isdel)
                {
                    return new ApiResult<int>
                    {
                        Msg = "出库单不存在",
                        Code = ApiEnum.Failed
                    };
                }

                // 更新出库单信息
                _mapper.Map(request, stockOutOrder);

                // 保存修改
               await _stockOutOrderRepository.Update(stockOutOrder);

                // 返回成功结果
                return new ApiResult<int>
                {
                    Code = ApiEnum.Success,
                    Msg = "修改成功",
                    Data = stockOutOrder.Id
                };
            }
            catch (Exception ex)
            {
                // 异常时返回错误信息
                return new ApiResult<int>
                {
                    Code = ApiEnum.Failed,
                    Msg = $"修改失败，{ex.Message}",
                };
            }
        }
    }
}